﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
using System.Collections;
using System.Security;

namespace PoshXmpp
{
    [Cmdlet(VerbsCommon.Get, "Contact")]
    public class GetContactCommand : XmppCommandBase
    {
        #region Parameters

        [Parameter(Position = 0,
        HelpMessage = "Name to look for")]
        public WildcardPattern Name { get; set; }

        [Parameter(Position = 1,
        HelpMessage = "How long to wait for server list")]
        public int WaitTime {
            get { return _waitTime; }
            set { _waitTime = value; }
        }
        int _waitTime = 1;
        #endregion

        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            List<string> shown = new List<string>();

            if( Client.ContactManager.Contacts.Count == 0 ) {
                _waitTime = Math.Max(10,_waitTime);
            }
            Client.RequestRoster();
            DateTime start = DateTime.Now;
            TimeSpan wait = TimeSpan.FromSeconds(_waitTime);

            // System.Threading.Thread.Sleep(wait);

            while (DateTime.Now - start < wait)
            {
                foreach (agsXMPP.Jid contact in Client.OnlineContacts)
                {
                    if (!shown.Contains(contact.ToString()))
                    {
                        WriteObject(contact);
                        shown.Add(contact.ToString());
                    }
                }
                System.Threading.Thread.Sleep( 100 );
            }
        }
    }
}
